package com.example.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.apis.schedule.IScheduleClient;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.common.enums.TaskTypeEnum;
import com.example.model.schedule.dtos.Task;
import com.example.model.wemedia.pojos.WmNews;
import com.example.utils.common.ProtostuffUtil;
import com.example.wemedia.service.WmNewsAutoScanService;
import com.example.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.swing.text.TabableView;
import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient iScheduleClient;

    @Override
    public void addNewsToTask(Integer id, Date publishTime) {

        log.info("添加任务到延迟服务中");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());

        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        iScheduleClient.addTask(task);
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;



    @Override
    @Scheduled(fixedDelay = 1000)
    public void scanNewsByTask() {

        ResponseResult responseResult = iScheduleClient.pull(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult.getCode().equals(200) && responseResult.getData() != null){
            String jsonString = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(jsonString, Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            wmNewsAutoScanService.autoScanNews(wmNews.getId());
            log.info("消费任务，审核文章 taskId {}",task.getTaskId());
        }
        log.info("消费任务，审核文章");
    }


}
